﻿using System;

namespace WPHttpServer
{
    public class RedirectResponse : HttpResponse
    {
        public string RedirectTo
        {
            get
            {
                if (this.Headers.ContainsKey(HttpConstants.LOCATION_HEADER_NAME))
                {
                    return this.Headers[HttpConstants.LOCATION_HEADER_NAME];
                }
                else
                {
                    return null;
                }
            }
        }

        public RedirectResponse(string redirectToAbsolute) : base(HttpStatusCode.Found)
        {
            if (!redirectToAbsolute.ToLower().StartsWith("http"))
            {
                throw new FormatException("The given adress is not ab absolute adress");
            }

            this.Headers.Add(HttpConstants.LOCATION_HEADER_NAME, redirectToAbsolute);
        }

        public RedirectResponse(string redirectToRelative, HttpServer associatedServer)
            : base(HttpStatusCode.Found)
        {
            if (redirectToRelative.StartsWith("/"))
            {
                // remove the first "/"
                redirectToRelative = redirectToRelative.Substring(1);
            }

            string absoluteUrl = string.Format("http://{0}:{1}/{2}",
                                               associatedServer.Domain,
                                               associatedServer.ServiceName,
                                               redirectToRelative);

            this.Headers.Add(HttpConstants.LOCATION_HEADER_NAME, absoluteUrl);
        }
    }
}
